package com.fy.login;

import javax.security.auth.Subject;
import javax.security.auth.login.LoginException;
import java.security.AccessControlException;
import java.security.PrivilegedAction;
import java.text.MessageFormat;
import java.util.Date;
import java.util.Locale;

/**
 * @author zhufeifei 2022/8/28
 **/

public class AppTest {
    public static void main(String[] args) throws LoginException {
        if (System.getSecurityManager() == null) {
            System.setSecurityManager(new SecurityManager());
        }


        EventListeners.register(EventListeners.Type.LOGIN,
                (metadata, subject) -> {
                    System.out.println(MessageFormat.format("{0,date,full},【{1}】已登陆",new Date(), metadata.getUsername()));
                });

        EventListeners.register(EventListeners.Type.LOGOUT,
                (metadata, subject) -> {
                    System.out.println(MessageFormat.format("{0,date,full},【{1}】已登出",new Date(), metadata.getUsername()));
                });


        LoginContextWrapper wrapper = LoginManager.login(LoginType.TEMPORARY,
                new NetCallbackHandler(Role.USER, "zolmk", "123".toCharArray(),"127.0.0.0", 23456));


        String userDir = Subject.doAsPrivileged(wrapper.getSubject(), new SysPropAction("user.dir"), null);

        System.out.printf("获取【user.dir】=【%s】\n", userDir);

        try {
            Subject.doAsPrivileged(wrapper.getSubject(), (PrivilegedAction<Void>) () -> {
                System.setProperty("user.dir", "/root");
                return null;
            }, null);
        } catch (AccessControlException e) {
            System.out.println("设置【user.dir】失败！");
        }


        wrapper.logout();


    }
}
